package com.example.studentgrades.controller;

import com.example.studentgrades.util.ConnectionManager;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {
    protected Connection getConnection() throws SQLException {
        return ConnectionManager.getConnection();
    }

    protected void forwardToPage(HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, IOException {
        request.getRequestDispatcher(page).forward(request, response);
    }

    protected void redirectToPage(HttpServletResponse response, String page) throws IOException {
        response.sendRedirect("../"+page);
    }

    protected void handleSQLException(HttpServletResponse response, SQLException e, String redirectPage) throws IOException {
        e.printStackTrace(); // 打印异常信息
        response.sendRedirect(redirectPage); // 重定向到指定页面
    }
}
